<template>
  <div>
    <el-carousel
      :interval="5000"
      :height="height+'px'"
      indicator-position="none"
    >
      <el-carousel-item
        v-for="(sensor,index2) in sensorList"
        v-if="showHidden === '1' || !sensor.hidden"
        :key="index2"
        style="padding: 0 8px"
      >
        <div style="height: 30px;display: flex;justify-content: space-between">
          <div v-if="sensor.editSensor == true" style="margin-top: 5px">
            <el-input v-model="sensor.sensorName">
              <el-button slot="append" icon="el-icon-check" @click="updateSensorName(sensor)"/>
            </el-input>
          </div>
          <div
            v-else
            style="line-height: 30px;font-size:15px;margin-left: 5px"
            @click="editSensor(sensor)"
          >
            <span style="color: #909399;">{{ formatSensorType(sensor.type) }}{{ $t('port') }}:{{ sensor.port }}</span>
            <span style="margin-left: 5px;color: #34bfa3">{{ sensor.sensorName }}</span>
          </div>
          <el-row style="float: right">
            <el-popover
              placement="bottom"
              width="200"
              trigger="hover"
            >
              <div>
                <div v-if="devModel" class="config-item" @click="gotoParam(sensor)">
                  <div style="line-height: 30px;font-size:15px" class="primary-color">{{
                      $t('param') + $t('manage')
                    }}
                  </div>
                </div>
                <div v-if="devModel" class="config-item" @click="gotoExplain(sensor)">
                  <div style="line-height: 30px;font-size:15px" class="primary-color">{{
                      $t('explain') + $t('manage')
                    }}
                  </div>
                </div>
                <div v-if="devModel" class="config-item" @click="gotoSetting(sensor)">
                  <div style="line-height: 30px;font-size:15px" class="primary-color">{{
                      $t('setting') + $t('manage')
                    }}
                  </div>
                </div>
                <div class="config-item" @click="gotoComparison(sensor)">
                  <div style="line-height: 30px;font-size:15px" class="primary-color">{{
                      $t('explain') + $t('comparison')
                    }}
                  </div>
                </div>
              </div>
              <el-button
                slot="reference"
                style="margin-left: 13px"
                type="text"
                icon="el-icon-caret-bottom"
              />
            </el-popover>
            <el-button
              style="margin-left: 13px"
              type="text"
              :disabled="sensor.explainList.length < 1"
              @click="gotoSensorRealTime(sensor)"
            >{{ $t('realTime') }}
            </el-button>
            <el-button
              style="margin-left: 13px"
              type="text"
              :disabled="sensor.saveInterval < 0 || sensor.explainList.length < 1"
              @click="gotoSensorHistory(sensor)"
            >{{ $t('history') }}
            </el-button>
          </el-row>
        </div>
        <template v-if="showExplainList === '1'">
          <el-row :gutter="0">
            <el-col
              v-for="(explain,index3) in sensor.explainList"
              v-if="showHidden === '1' || !explain.hidden"
              :key="index3"
              :span="6"
            >
              <div class="item">
                <div
                  style="color: #909399;font-size: 13px;text-align: center;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;"
                >
                  <el-popover
                    v-if="explain.remark && explain.remark!==''"
                    placement="top"
                    width="200"
                    trigger="hover"
                    :content="explain.name"
                  >
                    <span slot="reference">{{ explain.remark }}</span>
                  </el-popover>
                  <span v-else>{{ explain.name }}</span>
                </div>
                <div
                  style="color: #34bfa3;font-size: 20px;text-align: center;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;"
                >
                  <span>{{ explain.value }}</span>
                  <span style="font-size: 12px">{{ explain.unit }}</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </template>
      </el-carousel-item>
    </el-carousel>

    <el-dialog
      :visible.sync="showExplainData"
      :title="explain.name"
      destroy-on-close
      width="1300px"
      top="15px"
    >
      <explain-info v-if="showExplainData" :explain="explain"/>
    </el-dialog>

  </div>
</template>

<script>
import { formatSensorType, successNotice } from '@/util/common'
import { listSensorWith, updateSensor } from '@/api/iot/iotDeviceSensorApi'
import ExplainInfo from '@/components/DeviceExplainInfo/index'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'
import { getDevModel } from '@/util/storage'

export default {
  name: 'DeviceSensor',
  components: {
    ExplainInfo
  },
  props: {
    device: {
      type: Object,
      default: null
    },
    showExplainList: {
      type: String,
      default: '1'
    },
    showParamList: {
      type: String,
      default: '1'
    },
    showHidden: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      sensorList: [],
      showExplainData: false,
      explain: {},
      // ws: null,
      lastDeviceCore: null,
      height: 0,
      wsMonitor: {
        room: 'iot:device:' + this.device.deviceCore,
        onmessage: this.onSocketMsg
      },
      devModel: getDevModel() === 'true'
    }
  },
  watch: {
    device: {
      deep: true,
      handler(val) {
        if (this.device && this.device.deviceCore) {
          this.listSensorWith()
          if (this.lastDeviceCore != null) {
            leaveWebSocket(this.wsMonitor)
            // this.ws.send(JSON.stringify({
            //   cmd: 'unBindRoom',
            //   param: 'iot:device:' + this.lastDeviceCore
            // }))
          }
          this.wsMonitor.room = 'iot:device:' + this.device.deviceCore
          listenWebSocket(this.wsMonitor)
          // this.ws.send(JSON.stringify({
          //   cmd: 'bindRoom',
          //   param: 'iot:device:' + this.device.deviceCore
          // }))
          this.lastDeviceCore = this.device.deviceCore
        }
      }
    }
  },
  beforeDestroy() {
    // this.ws.send(JSON.stringify({
    //   cmd: 'unBindRoom',
    //   param: 'iot:device:' + this.device.deviceCore
    // }))
    // this.ws.close()
    this.closeSocket()
  },
  created() {
    if (this.device.deviceCore != null) {
      this.lastDeviceCore = this.device.deviceCore
      this.listSensorWith()
    }
    // this.initSocket()
    this.wsMonitor.room = 'iot:device:' + this.device.deviceCore
    listenWebSocket(this.wsMonitor)
  }, methods: {
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'deviceData') {
        const data = JSON.parse(nowData.msg)
        // console.log(data)
        if (data.deviceUpload) {
          if (data.deviceUpload.setting) {
            this.sensorList.forEach(deviceSensor => {
              if (deviceSensor.settingList && deviceSensor.settingList.length > 0) {
                for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
                  const deviceSetting = deviceSensor.settingList[i]
                  if (data.deviceUpload.setting.keyName === deviceSetting.keyName && data.deviceUpload.setting.port === deviceSetting.port) {
                    deviceSetting.value = data.deviceUpload.setting.value
                    deviceSetting.valueDate = nowData.updateDate
                    deviceSensor.settingList.splice(i, 1, deviceSetting)
                  }
                }
              }
            })
          }
          if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
            data.deviceUpload.sensorList.forEach(sensor => {
              that.sensorList.forEach(deviceSensor => {
                if (sensor.port === deviceSensor.port) {
                  if (sensor.explainList && sensor.explainList.length > 0 && deviceSensor.explainList && deviceSensor.explainList.length > 0) {
                    sensor.explainList.forEach(explain => {
                      for (let i = 0, j = deviceSensor.explainList.length; i < j; i++) {
                        const deviceExplain = deviceSensor.explainList[i]
                        if (explain.keyName === deviceExplain.keyName) {
                          deviceExplain.lastValue = deviceExplain.value
                          deviceExplain.lastRawValue = deviceExplain.rawValue
                          deviceExplain.value = explain.value
                          deviceExplain.rawValue = explain.rawValue
                          deviceExplain.valueDate = nowData.timestamp
                          deviceSensor.explainList.splice(i, 1, deviceExplain)
                        }
                      }
                    })
                  }
                  if (sensor.paramList && sensor.paramList.length > 0 && deviceSensor.paramList && deviceSensor.paramList.length > 0) {
                    sensor.paramList.forEach(param => {
                      for (let i = 0, j = deviceSensor.paramList.length; i < j; i++) {
                        const deviceParam = deviceSensor.paramList[i]
                        if (param.keyName === deviceParam.keyName) {
                          deviceParam.value = param.value
                          deviceParam.valueDate = nowData.updateDate
                          deviceSensor.paramList.splice(i, 1, deviceParam)
                        }
                      }
                    })
                  }
                  if (sensor.settingList && sensor.settingList.length > 0 && deviceSensor.settingList && deviceSensor.settingList.length > 0) {
                    sensor.settingList.forEach(setting => {
                      for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
                        const deviceSetting = deviceSensor.settingList[i]
                        if (setting.keyName === deviceSetting.keyName) {
                          deviceSetting.value = setting.value
                          deviceSetting.valueDate = nowData.updateDate
                          deviceSensor.settingList.splice(i, 1, deviceSetting)
                        }
                      }
                    })
                  }
                }
              })
            })
          }
        }
      }
    },
    // initSocket() {
    //   const that = this
    //   this.ws = newWebSocket()
    //   this.ws.onopen = () => {
    //     that.wsConnected = true
    //     that.ws.send(JSON.stringify({
    //       cmd: 'bindRoom',
    //       param: 'iot:device:' + that.device.deviceCore
    //     }))
    //   }
    //   this.ws.onerror = function(e) {
    //     that.wsConnected = false
    //     console.error('WebSocket is error' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     that.ws.close()
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 10000)
    //   }
    //   this.ws.onclose = function(e) {
    //     that.wsConnected = false
    //     console.error('WebSocket is close' + e.code + ' ' + e.reason + ' ' + e.wasClean)
    //     setTimeout(function() {
    //       that.initSocket()
    //     }, 10000)
    //   }
    //   this.ws.onmessage = function(msg) {
    //     const nowData = JSON.parse(msg.data)
    //     if (nowData.type === 'deviceData') {
    //       const data = JSON.parse(nowData.msg)
    //       // console.log(data)
    //       if (data.deviceUpload) {
    //         if (data.deviceUpload.setting) {
    //           that.sensorList.forEach(deviceSensor => {
    //             if (deviceSensor.settingList && deviceSensor.settingList.length > 0) {
    //               for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
    //                 const deviceSetting = deviceSensor.settingList[i]
    //                 if (data.deviceUpload.setting.keyName === deviceSetting.keyName && data.deviceUpload.setting.port === deviceSetting.port) {
    //                   deviceSetting.value = data.deviceUpload.setting.value
    //                   deviceSetting.valueDate = nowData.updateDate
    //                   deviceSensor.settingList.splice(i, 1, deviceSetting)
    //                 }
    //               }
    //             }
    //           })
    //         }
    //         if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
    //           data.deviceUpload.sensorList.forEach(sensor => {
    //             that.sensorList.forEach(deviceSensor => {
    //               if (sensor.port === deviceSensor.port) {
    //                 if (sensor.explainList && sensor.explainList.length > 0 && deviceSensor.explainList && deviceSensor.explainList.length > 0) {
    //                   sensor.explainList.forEach(explain => {
    //                     for (let i = 0, j = deviceSensor.explainList.length; i < j; i++) {
    //                       const deviceExplain = deviceSensor.explainList[i]
    //                       if (explain.keyName === deviceExplain.keyName) {
    //                         deviceExplain.lastValue = deviceExplain.value
    //                         deviceExplain.lastRawValue = deviceExplain.rawValue
    //                         deviceExplain.value = explain.value
    //                         deviceExplain.rawValue = explain.rawValue
    //                         deviceExplain.valueDate = nowData.timestamp
    //                         deviceSensor.explainList.splice(i, 1, deviceExplain)
    //                       }
    //                     }
    //                   })
    //                 }
    //                 if (sensor.paramList && sensor.paramList.length > 0 && deviceSensor.paramList && deviceSensor.paramList.length > 0) {
    //                   sensor.paramList.forEach(param => {
    //                     for (let i = 0, j = deviceSensor.paramList.length; i < j; i++) {
    //                       const deviceParam = deviceSensor.paramList[i]
    //                       if (param.keyName === deviceParam.keyName) {
    //                         deviceParam.value = param.value
    //                         deviceParam.valueDate = nowData.updateDate
    //                         deviceSensor.paramList.splice(i, 1, deviceParam)
    //                       }
    //                     }
    //                   })
    //                 }
    //                 if (sensor.settingList && sensor.settingList.length > 0 && deviceSensor.settingList && deviceSensor.settingList.length > 0) {
    //                   sensor.settingList.forEach(setting => {
    //                     for (let i = 0, j = deviceSensor.settingList.length; i < j; i++) {
    //                       const deviceSetting = deviceSensor.settingList[i]
    //                       if (setting.keyName === deviceSetting.keyName) {
    //                         deviceSetting.value = setting.value
    //                         deviceSetting.valueDate = nowData.updateDate
    //                         deviceSensor.settingList.splice(i, 1, deviceSetting)
    //                       }
    //                     }
    //                   })
    //                 }
    //               }
    //             })
    //           })
    //         }
    //       }
    //     }
    //   }
    // },
    updateSensorName(item) {
      updateSensor({
        sensorId: item.sensorId,
        sensorName: item.sensorName
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        for (const i in this.sensorList) {
          if (this.sensorList[i].sensorId === item.sensorId) {
            item.editSensor = false
            this.sensorList.splice(i, 1, item)
            break
          }
        }
      })
    },
    editSensor(item) {
      for (const i in this.sensorList) {
        if (this.sensorList[i].sensorId === item.sensorId) {
          item.editSensor = true
          this.sensorList.splice(i, 1, item)
          break
        }
      }
    },
    gotoSensorHistory(sensor) {
      this.$router.push({
        path: '/device/sensor/history/' + sensor.sensorId,
        query: {
          'deviceCore': this.device.deviceCore,
          'deviceName': this.device.deviceName,
          'sensorId': sensor.sensorId,
          'sensorName': sensor.sensorName,
          'port': sensor.port
        }
      })
    },
    gotoSensorRealTime(sensor) {
      this.$router.push({
        path: '/device/sensor/real-time/' + sensor.sensorId,
        query: {
          'deviceCore': this.device.deviceCore,
          'deviceName': this.device.deviceName,
          'sensorId': sensor.sensorId,
          'sensorName': sensor.sensorName,
          'port': sensor.port
        }
      })
    },
    gotoSensor() {
      this.$router.push({
        path: '/device/sensor/' + this.device.deviceCore,
        query: {
          'deviceCore': this.device.deviceCore,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoParam(sensor) {
      this.$router.push({
        path: '/device/param/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoSetting(sensor) {
      this.$router.push({
        path: '/device/setting/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoExplain(sensor) {
      this.$router.push({
        path: '/device/explain/' + this.device.deviceCore,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    gotoComparison(sensor) {
      this.$router.push({
        path: '/device/sensor/analysis/' + sensor.sensorId,
        query: {
          'port': sensor.port,
          'deviceCore': this.device.deviceCore,
          'sensorId': sensor.sensorId,
          'type': sensor.type,
          'sensorName': sensor.sensorName,
          'deviceName': this.device.deviceName
        }
      })
    },
    formatSensorStatus(status) {
      if (this.device.status !== 'ONLINE') {
        return '[' + this.$t('OFFLINE') + ']'
      }
      if (status !== 'UNKNOW') {
        return '[' + this.$t(status) + ']'
      }
      return ''
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    explainClick(item) {
      this.explain = item
      this.showExplainData = true
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.device.deviceCore,
        withExplain: true,
        withParam: true,
        withSetting: false
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const sensorList = []
          let maxExplainCount = 0
          for (const item of data) {
            if (!item.explainList) {
              item.explainList = []
            }
            if (!item.settingList) {
              item.settingList = []
            }
            if (!item.paramList) {
              item.paramList = []
            }
            if (item.explainList.length > 0 || item.settingList.length > 0 || item.paramList.length > 0) {
              sensorList.push(item)
            }
            if (item.explainList.length > maxExplainCount) {
              maxExplainCount = item.explainList.length
            }
          }
          this.height = 80 + maxExplainCount / 4 * 75
          console.log(this.height)
          this.sensorList = sensorList
        } else if (code === '201') {
          this.sensorList = []
        }
      })
    }
  }
}
</script>

<style scoped>

.item {
  border-radius: 20px;
  width: 100%;
  margin: 5px;
  padding: 8px;
  height: 60px;
}

.item:hover {
  background: #E4E7ED;
}

.config-item {
  margin-top: 2px;
  padding: 3px;
  /*box-shadow: 0 2px 12px 0 rgba(0,0,0,.2);*/
  border-radius: 5px;
  height: 35px;
  width: 100%;
  display: flex;
  justify-content: space-between
}

.config-item:hover {
  background: #E4E7ED;
}

</style>
